﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "windows.h"
#include "QWindow.h"
#include <iostream>
#include <QApplication>
#include <QClipboard>
#include <QMimeData>
#include <QDebug>

#include <QFileDialog>
#include <QDebug>

using namespace std;

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //QVBoxLayout* layout = new QVBoxLayout(this);

    //outputDisplay = new QTextEdit(this);
    //outputDisplay->setReadOnly(true);
    //ui->gridLayout->addWidget(outputDisplay);
    //layout->addWidget(outputDisplay);

    connect(ui->pb_postProcessing, &QPushButton::clicked, this, &MainWindow::slot_openPostProcessingModel);
    connect(ui->pb_openReportModel, &QPushButton::clicked, this, &MainWindow::slot_openReportModel);
    connect(ui->pb_screenShoot, &QPushButton::clicked, this, &MainWindow::slot_screenshoot);
    connect(ui->pb_screenshootToReport, &QPushButton::clicked, this, &MainWindow::slot_screenshootToReport);

    //setLayout(layout);
    setWindowTitle("Run External EXE Example");
    //resize(400, 300);
}

MainWindow::~MainWindow()
{
    if (m_process)
    {
        m_process->close();
        delete m_process;
        m_process = Q_NULLPTR;
    }
    if (m_report)
    {
        m_report->close();
        delete m_report;
        m_report = Q_NULLPTR;
    }
    if (m_widget)
    {
        ui->postWidget->layout()->removeWidget(m_widget);
        delete m_widget;
        m_widget = Q_NULLPTR;
    }

    delete ui;
}

void MainWindow::slot_openPostProcessingModel()
{
    hideAllSubWindow();
    runExternalProcess();

}
void MainWindow::slot_openReportModel()
{
    hideAllSubWindow();
    InitChildReportProcess();

}

void MainWindow::slot_screenshoot()
{
    //调用Windows自带截图
    ShellExecuteA(NULL, "open", "cmd.exe", "/c start ms-screenclip:screenclip", NULL, 0);
}

void MainWindow::slot_screenshootToReport()
{
    //生成报告进程exe还未启动时，先启动，再发信号
    if (!m_report)
    {
        slot_openReportModel();
    }
    //调用GenerateReport.exe
    QByteArray command("{--}screenshootToReport{||}YES{--}\n");
    std::cout << "screenshootToReport" << std::endl;
    m_report->write(command);

}

void MainWindow::runExternalProcess()
{
    //process = new QProcess(this);

    //// 连接标准输出和错误输出  
    //connect(process, &QProcess::readyReadStandardOutput, this, &MainWindow::readOutput);
    //connect(process, &QProcess::readyReadStandardError, this, &MainWindow::readError);

    //// 启动外部程序 (请替换为你要运行的程序路径)  
    ////process->start("D:/WorkSpace/IDAProject/EXEDIR/PostProcessing.exe");
    //process->start("E:/openSourceCode/QtDesKBrowser/QWebWidgetDemo/build/bin/Debug/QWebWidget.exe", QStringList());

    //if (!process->waitForStarted())
    //{
    //    outputDisplay->append("Failed to start process.");
    //}
    //WId m_wid = (WId)FindWindow(NULL, "PostProcessing");

    //QWindow* M_WINDOW = QWindow::fromWinId(m_wid);
    //if (M_WINDOW == NULL)
    //{
    //    return;
    //}
    //QWidget* childWidget = QWidget::createWindowContainer(M_WINDOW, this);//创建新的widget
    //ui->gridLayout->addWidget(childWidget);//将widget窗口加入到主界面布局中
    ////childWidget->show();

    InitChildProcess();
}


void MainWindow::InitChildProcess()
{
    if (!m_process)
    {
#ifdef _DEBUG
        QString cmd = "./PostProcessing.exe";	//子程序文件路径
#else 
        QString cmd = "D:/WorkSpace/IDA_desk_app/output/bin/PostProcessing.exe";	//子程序文件路径
#endif
        m_process = new QProcess(this);	//使用进程运行子进程窗口
        connect(m_process, &QProcess::readyReadStandardOutput, this, &MainWindow::handleChildProcessMsg);
        m_process->setReadChannel(QProcess::StandardOutput);
        QStringList argList;
        //argList << "C:/LocalTemplates/北航电磁/总体专业系统/Work/hirf/"
        //    << QStringLiteral("C:/LocalTemplates/北航电磁/总体专业系统/Work/后处理");

        argList << QStringLiteral("E:/同济")
            << QStringLiteral("E:/同济/截图文件夹");

        m_process->start(cmd, argList);	//把父窗口的id传到子进程中
        //QByteArray command("{--}url{||}http://www.baidu.com{--}\n");
        //m_process->write(command);
    }
}

void MainWindow::InitChildReportProcess()
{
    if (!m_report)
    {
#ifdef _DEBUG
        QString cmd = "F:/IDA_desk_app/output/bin/GenerateReport.exe";	//子程序文件路径
#else 
        QString cmd = "F:/IDA_desk_app/output/bin/GenerateReport.exe";	//子程序文件路径
#endif
        m_report = new QProcess(this);	//使用进程运行子进程窗口
        connect(m_report, &QProcess::readyReadStandardOutput, this, &MainWindow::handleChildReportProcessMsg);
        m_report->setReadChannel(QProcess::StandardOutput);
        m_report->start(cmd, QStringList());	//把父窗口的id传到子进程中
        QByteArray command("{--}screenshootToReport{||}NO{--}\n");
        std::cout << "ReportProcess" << std::endl;
        m_report->write(command);
    }
}


void MainWindow::readOutput()
{
}

void MainWindow::readError()
{
}

void MainWindow::hideAllSubWindow()
{

}

void MainWindow::handleChildProcessMsg()
{
    //处理子进程消息

    QString msg = m_process->readAllStandardOutput();
    QStringList list_str = msg.split("{--}");
    qDebug() << QString("Child process msg: {%1}").arg(msg);

    foreach(auto var, list_str)
    {
        if (!(var.isEmpty()))
        {
            auto list_info = var.split("{||}");
            if (list_info.count() == 2 && list_info[0] == "winId")
            {
                quint64 winId = list_info[1].toLongLong();
                auto childWin = QWindow::fromWinId(winId);
                /// 子程序的widget窗口
                m_widget = QWidget::createWindowContainer(childWin, ui->postWidget, Qt::Widget);

                /// 将子程序的widget窗口加入到主界面
                auto layout = ui->postWidget->layout();
                //auto layout = ui->gridLayout;
                if (layout)
                {
                    layout->addWidget(m_widget);
                }
                else
                {
                    layout = new QGridLayout();
                    layout->setContentsMargins(0, 0, 0, 0);
                    layout->addWidget(m_widget);
                    ui->centralwidget->setLayout(layout);
                }
                break;
            }
        }
    }

}

void MainWindow::handleChildReportProcessMsg()
{
    //处理子进程消息

    QString msg = m_report->readAllStandardOutput();
    QStringList list_str = msg.split("{--}");
    qDebug() << QString("Child process msg: {%1}").arg(msg);

    foreach(auto var, list_str)
    {
        if (!(var.isEmpty()))
        {
            auto list_info = var.split("{||}");
            if (list_info.count() == 2 && list_info[0] == "winId")
            {
                quint64 winId = list_info[1].toLongLong();
                auto childWin = QWindow::fromWinId(winId);
                m_widget = QWidget::createWindowContainer(childWin, ui->postWidget, Qt::Widget);
                auto layout = ui->postWidget->layout();
                //auto layout = ui->gridLayout;
                if (layout)
                {
                    layout->addWidget(m_widget);
                }
                else
                {
                    layout = new QGridLayout();
                    layout->setContentsMargins(0, 0, 0, 0);
                    layout->addWidget(m_widget);
                    ui->centralwidget->setLayout(layout);
                }
                break;
            }
        }
    }

}
